<template>
  <div class="departments">
    <el-card>
      <template #header>
        <span>组织架构</span>
      </template>
      <div class="main">
        <treeItem :item-data="topTreeData" />
        <hr>
        <el-tree :data="treeData">
          <template v-slot="{ data }">
            <treeItem :item-data="data" @getData="getData" />
          </template>
        </el-tree>
      </div>
      <add :raw-data="rawData" @getData="getData" />
    </el-card>
  </div>
</template>

<script>
import treeItem from './components/treeItem.vue'
import { companyDepartment } from '@/api/departments.js'
import add from './components/add.vue'
export default {
  components: {
    treeItem,
    add
  },
  data: function() {
    return {
      topTreeData: {
        topTree: true,
        name: '江西传智播客教育科技股份有限公司',
        manager: '负责人',
        id: ''
      },
      treeData: [], // 员工基础数据
      rawData: [] // 原始数据
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await companyDepartment()
      this.rawData = res.data.depts
      this.treeData = this.changeData(res.data.depts, '')
    },
    // 树形数据结构转换
    changeData(arr, str) {
      return arr.filter((item) => {
        if (item.pid === str) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.departments {
  padding: 15px;
  .main {
    margin: 0 auto;
    width: 80%;
  }
}
</style>
